package com.it.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.common.R;
import com.it.server.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.it.pojo.Task;

import java.util.HashMap;
import java.util.Map;

/**
 * 任务信息Controller
 */
@RestController
@RequestMapping("/task")
public class TaskController {
    @Autowired
    private TaskService taskService;

    @GetMapping
    public Map<String, Object> list(Task task,
                                       @RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Task> pageInfo = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        // 构建查询条件
        if (task.getProjectId() != null) {
            wrapper.eq(Task::getProjectId, task.getProjectId());
        }
        if (task.getTaskId() != null) {
            wrapper.eq(Task::getTaskId, task.getTaskId());
        }
        if (StringUtils.isNotBlank(task.getName())) {
            wrapper.like(Task::getName, task.getName());
        }
        if (StringUtils.isNotBlank(task.getStatus())) {
            wrapper.eq(Task::getStatus, task.getStatus());
        }
        if (task.getAssignedTo() != null) {
            wrapper.eq(Task::getAssignedTo, task.getAssignedTo());
        }
        if (task.getDescription() != null) {
            wrapper.eq(Task::getDescription, task.getDescription());
        }
        if (task.getStartDate() != null && task.getEndDate() != null) {
            wrapper.between(Task::getStartDate, task.getStartDate(), task.getEndDate());
        }

        IPage<Task> result = taskService.page(pageInfo, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("rows", result.getRecords());
        data.put("total", result.getTotal());

        return data;
    }

    @GetMapping("{taskId}")
    public R<Task> getInfo(@PathVariable Long taskId) {
        return R.success(taskService.getById(taskId));
    }

    @PostMapping
    public R<Boolean> add(@RequestBody Task task) {
        return R.success(taskService.save(task));
    }

    @PutMapping
    public R<Boolean> edit(@RequestBody Task task) {
        return R.success(taskService.updateById(task));
    }

    @DeleteMapping("/{taskId}")
    public R<Boolean> remove(@PathVariable Long taskId) {
        return R.success(taskService.removeById(taskId));
    }
}